package com.by.component.extra;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.by.component.extra.dto.ExtraInfoSDTO;
import com.by.component.extra.mapper.ExtraInfoMapper;
import com.by.toolkit.utils.RetryUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.Map;

import static com.by.toolkit.utils.ExceptionUtil.*;

@Slf4j
@DubboService
public class ExtraInfoServiceImpl implements ExtraInfoService {

    @Resource
    private ExtraInfoMapper extraInfoMapper;

    @Override
    public String buildExtraCode(Integer extraType, Map<String, Object> content) {
        nullError(content, "内容不能为空");

        return RetryUtil.retryIfResult(() -> {
                    String extraCode = IdUtil.fastSimpleUUID();
                    try {
                        extraInfoMapper.insert(ExtraInfo.builder()
                                .extraCode(extraCode)
                                .extraType(extraType)
                                .extraContent(JSON.toJSONString(content))
                                .build());
                    } catch (Exception e) {
                        if (uqIndexError(e)) {
                            return null;
                        }
                        log.warn("[ExtraInfoServiceImpl][buildExtraCode] hasException:[{}] ", getStackTrace(e));
                        return null;
                    }
                    return extraCode;
                }, StringUtils::isBlank
                , 5
                , 100);
    }

    @Override
    public ExtraInfoSDTO resolveExtraCode(String extraCode) {
        ExtraInfo extraInfo = extraInfoMapper.selectOne(Wrappers.lambdaQuery(ExtraInfo.class)
                .select(ExtraInfo::getExtraType,
                        ExtraInfo::getExtraContent)
                .eq(ExtraInfo::getExtraCode, extraCode));
        nullError(extraInfo, "扩展信息不存在");
        return ExtraInfoSDTO.builder()
                .extraType(extraInfo.getExtraType())
                .content(JSON.parseObject(extraInfo.getExtraContent()))
                .build();
    }
}
